package com.ruoyi.bpm.service.definition.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.ruoyi.bpm.controller.admin.definition.vo.form.BpmFormPageReqVO;
import com.ruoyi.bpm.controller.admin.definition.vo.form.BpmFormSaveReqVO;
import com.ruoyi.bpm.domain.definition.BpmForm;
import com.ruoyi.bpm.enums.ErrorCodeConstants;
import com.ruoyi.bpm.mapper.definition.BpmFormMapper;
import com.ruoyi.bpm.service.definition.BpmFormService;
import com.ruoyi.bpm.service.definition.dto.BpmFormFieldRespDTO;
import com.ruoyi.bpm.utils.BeanUtils;
import com.ruoyi.common.json.utils.JsonUtils;
import com.ruoyi.common.orm.core.page.PageQuery;
import com.ruoyi.common.orm.core.page.TableDataInfo;
import com.ruoyi.common.orm.core.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.*;

import static com.ruoyi.bpm.domain.category.table.BpmCategoryTableDef.BPM_CATEGORY;
import static com.ruoyi.bpm.domain.definition.table.BpmFormTableDef.BPM_FORM;
import static com.ruoyi.common.core.utils.ServiceExceptionUtil.exception;

/**
 * 动态表单 Service 实现类
 *
 * @author 风里雾里
 */
@Service
@Validated
public class BpmFormServiceImpl extends BaseServiceImpl<BpmFormMapper, BpmForm> implements BpmFormService {
    @Override
    public QueryWrapper query() {
        return super.query().from(BPM_FORM);
    }

    @Override
    public Long createForm(BpmFormSaveReqVO createReqVO) {
        this.validateFields(createReqVO.getFields());
        // 插入
        BpmForm form = BeanUtils.toBean(createReqVO, BpmForm.class);
        mapper.insert(form);
        // 返回
        return form.getId();
    }

    @Override
    public void updateForm(BpmFormSaveReqVO updateReqVO) {
        validateFields(updateReqVO.getFields());
        // 校验存在
        validateFormExists(updateReqVO.getId());
        // 更新
        BpmForm updateObj = BeanUtils.toBean(updateReqVO, BpmForm.class);
        mapper.update(updateObj);
    }

    @Override
    public void deleteForm(Long id) {
        // 校验存在
        this.validateFormExists(id);
        // 删除
        mapper.deleteById(id);
    }

    private void validateFormExists(Long id) {
        if (getForm(id) == null) {
            throw exception(ErrorCodeConstants.FORM_NOT_EXISTS);
        }
    }

    @Override
    public BpmForm getForm(Long id) {
        return super.getById(id);
    }

    @Override
    public List<BpmForm> getFormList() {
        return super.list();
    }

    @Override
    public List<BpmForm> getFormList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        return super.listByIds(ids);
    }

    @Override
    public TableDataInfo<BpmForm> getFormPage(BpmFormPageReqVO pageReqVO) {
        QueryWrapper queryWrapper = query()
            .where(BPM_FORM.NAME.like(pageReqVO.getName(), StrUtil.isNotBlank(pageReqVO.getName())))
            .orderBy(BPM_CATEGORY.ID.desc());
        Page<BpmForm> page = this.pageAs(PageQuery.build(), queryWrapper, BpmForm.class);
        return TableDataInfo.build(page);
    }

    /**
     * 校验 Field，避免 field 重复
     *
     * @param fields field 数组
     */
    private void validateFields(List<String> fields) {
        if (true) { // TODO 芋艿：兼容 Vue3 工作流：因为采用了新的表单设计器，所以暂时不校验
            return;
        }
        Map<String, String> fieldMap = new HashMap<>(); // key 是 vModel，value 是 label
        for (String field : fields) {
            BpmFormFieldRespDTO fieldDTO = JsonUtils.parseObject(field, BpmFormFieldRespDTO.class);
            Assert.notNull(fieldDTO);
            String oldLabel = fieldMap.put(fieldDTO.getVModel(), fieldDTO.getLabel());
            // 如果不存在，则直接返回
            if (oldLabel == null) {
                continue;
            }
            // 如果存在，则报错
            throw exception(ErrorCodeConstants.FORM_FIELD_REPEAT, oldLabel, fieldDTO.getLabel(), fieldDTO.getVModel());
        }
    }

}
